﻿using Enter.Admin.Entities;
using Enter.Admin.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;

namespace Enter.Admin.Filters
{
    public enum ActionRole
    { 
        User = 0,
        Admin = 1,
    }
    public class ActionFilter : IActionFilter
    {
        private ActionRole _role;
        public ActionFilter(ActionRole role = ActionRole.User)
        {
            _role = role;
        }
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // .HttpContext.Response.Redirect("./Login");
            var session = context.HttpContext.Session.Get<Employ>();
            if (session == default(Employ))
            {
                context.Result = new RedirectToRouteResult(new RouteValueDictionary
                {
                    { "controller", "Login" },
                    { "action", "Index" }
                });
                return;
            }
            else if (!session.Role.IsDefault && _role == ActionRole.Admin)
            {
                context.Result = new ContentResult() { 
                    Content="没有权限.",
                };
                return;
            }
            //context.HttpContext.Response.WriteAsync($"{GetType().Name} in. \r\n");
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            //filterContext.Result = new RedirectResult("customErrorPage.html");
            //context.HttpContext.Response.WriteAsync($"{GetType().Name} out. \r\n");
        }
    }
}
